package IO.io;

import com.sun.beans.finder.FieldFinder;
import org.junit.Test;

import java.io.*;

public class FileReaderWriterTest {

    @Test
    public void test(){
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");

            //2.FileReader流的实例化
            fr = new FileReader(file);

            //3.读入的操作
            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾，返回-1
            char[] cbuf = new char[5];
            int len;
            while((len = fr.read(cbuf)) != -1){

                //正确的写法
//                for(int i = 0;i < len;i++){
//                    System.out.print(cbuf[i]);
//                }

                //正确的写法
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
                //4.资源的关闭
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @Test
    public void testwrite(){
        FileWriter fw=null;
        try {
            File file = new File("hello.txt");
            fw = new FileWriter(file, true);
            fw.write("love! ");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fw !=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Test
    public void test2() {
        FileReader fr = null;
        FileWriter fw = null;

        //1.创建File类的对象，指明读入和写出的文件
        File srcFile = new File("hello.txt");
        File destFile = new File("hello2.txt");

        //2.创建输入流和输出流的对象
        try {
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);
            char[] str=new char[5];
            int len;
            while ((len=fr.read(str))!=-1){
                fw.write(str,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fr!=null)
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (fw!=null)
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

